package com.redsoft.epip.service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.redsoft.epip.dao.MemberRepository;
import com.redsoft.epip.entity.Member;
import com.redsoft.spirit.util.BeanUtils;
import com.vdurmont.emoji.EmojiParser;

/**
 * 后台会员管理的Service.
 * 
 * <pre>
 * 后台会员管理的Service
 * </pre>
 * 
 * @author
 * @since 1.0
 */
@Service
@Transactional
public class MemberService {

	@Autowired
	private MemberRepository memberRepository;

	/**
	 * 后台管理员查询列表获取列表
	 * 
	 * @param offset
	 * @param limit
	 * @param searchKey
	 * @return
	 */
	public Map<String, Object> getJson(int offset, int limit, String searchKey) {
		String sql = "select c.*, c2.NICKNAME refereeName "
				+ " from USER_INFO c "
				+ " left join USER_INFO c2 "
				+ " on c.REFEREE = c2.id "
				+ " where c.IS_DELETED = 0";
		String countSql = "select count(1) from USER_INFO c where c.IS_DELETED = 0";
		Map<String, Object> map = new HashMap<>();

		if (searchKey != null && !"".equals(searchKey)) {
			map.put("searchKey", "%" + searchKey + "%");
			sql += " and c.NICKNAME like :searchKey";
			countSql += " and c.NICKNAME like :searchKey";
		}
		return memberRepository.sqlQuery(sql, countSql, map, offset, limit, "total", "rows");
	}

	/**
	 * 根据id查询一条会员信息
	 * 
	 * <pre>
	 * 根据id查询一条会员信息
	 * </pre>
	 * 
	 * @author 杨雷
	 * @param id
	 * @return
	 */
	public Member getMemberById(String id) {
		Member member = memberRepository.getMemberById(id);
		return member;
	}

	/**
	 * 根据id删除一条会员信息
	 * 
	 * <pre>
	 * 根据id删除一条会员信息
	 * </pre>
	 * 
	 * @param id
	 */
	public void delete(String id) {
		memberRepository.deleteById(id);
	}

	/**
	 * 保存授权登录的用户信息
	 * 
	 * <pre>
	 * 保存授权登录的用户信息
	 * </pre>
	 * 
	 * @author 杨雷
	 * @param member
	 * @return
	 * @throws Exception
	 */
	public Member save(Member member) {
		member.setIsDeleted(0);
		
		Member memberOld = memberRepository.findByOpenId(member.getOpenId());
		if (memberOld == null) {
			System.out.println("=========>member.nickName: " + member.getNickname());
//			String result = EmojiParser.parseToHtmlDecimal(member.getNickname());
//			System.out.println("=========>emoji解析后的昵称： " + result);
			String result_hex = EmojiParser.parseToHtmlHexadecimal(member.getNickname());
			System.out.println("=========>emoji--parseToHtmlHexadecimal解析后的昵称result_hex： " + result_hex);
			member.setNickname(result_hex);
			member.setScore(0);
			member.setIsDraw(0);//新用户未领取优惠券
			member.setSubscribeTime(new Date());
			memberRepository.save(member);
			
			return member;
		} else {
			try {
				BeanUtils.copyBeanNotNull2Bean(member, memberOld);
			} catch (Exception e) {
				e.printStackTrace();
			}
			memberRepository.save(memberOld);
			
			return memberOld;
		}
	}

	/**
	 * 
	 * 给会员绑定手机号.
	 * <pre>
	 * 	给会员绑定手机号
	 * </pre>
	 * 
	 * @author 杨雷
	 * @param openId
	 * @param phoneNo
	 */
	public void bindPhoneNo(String userId, String phoneNo) {
		Member member = memberRepository.findOne(userId);
		member.setPhoneNo(phoneNo);
		
		memberRepository.save(member);
	}
	
	/**
	 * 
	 * 根据openId获取会员信息
	 * <pre>
	 * 根据openId获取会员信息
	 * </pre>
	 * 
	 * @author lixiaodong
	 * @param openId 会员微信openId
	 * @return
	 */
	public Member findByOpenId(String openId) {
		Member member = memberRepository.findByOpenId(openId);
		return member;
	}
	
	/**
	 * 
	 * 根据手机号获取实体类
	 * <pre>
	 * 根据手机号获取实体类
	 * </pre>
	 * 
	 * @author lixiaodong
	 * @param phoneNo
	 * @return
	 */
	public Member findByPhoneNo(String phoneNo) {
		Member member = memberRepository.findByPhoneNo(phoneNo);
		return member;
	}
	
	/**
	 * 
	 * 获取推荐关注用户列表
	 * <pre>
	 * 获取推荐关注用户列表
	 * </pre>
	 * 
	 * @author lixiaodong
	 * @param offset
	 * @param limit
	 * @param userId
	 * @param sinceId
	 * @param beginDate
	 * @param endDate
	 * @return
	 */
	public Map<String, Object> getScoreRefereeUsers(int offset, int limit, String userId, String sinceId, String beginDate, String endDate) {
		String sql0 = " select ui.id, ui.NICKNAME,ui.HEADIMGURL, ui.subscribe_time "
				+ " from user_info ui "
				+ " where 1 = 1 "
				+ " and ui.referee = :userId ";

		Map<String, Object> map = new HashMap<>();
		map.put("userId", userId);

		if (beginDate != null && !"".equals(beginDate)) {
			sql0 += " and TO_CHAR(ui.subscribe_time, 'yyyy-MM-dd HH:mm:ss') > :beginDate";
			map.put("beginDate", beginDate);
		}
		if (endDate != null && !"".equals(endDate)) {
			sql0 += " and TO_CHAR(ui.subscribe_time, 'yyyy-MM-dd HH:mm:ss') < :endDate";
			map.put("endDate", endDate);
		}
		sql0 += " order by ui.subscribe_time desc ";

		String sql = " select a.id, a.NICKNAME, a.HEADIMGURL, a.subscribe_time "
				+ " from ( " + sql0 + ") a "
				+ " where 1 = 1 ";
		if (sinceId != null && !"".equals(sinceId)) {
			sql += " and a.subscribe_time < (select b.subscribe_time from (" + sql0 + ") b where b.id = :sinceId) ";
			map.put("sinceId", sinceId);
		}
		String countSql = "select count(1) from (" + sql + ") temp1 ";

		return memberRepository.sqlQuery(sql, countSql, map, offset, limit, "total", "rows");
	}
	
	/**
	 * 
	 * 获取推荐关注用户数量排行榜
	 * <pre>
	 * 获取推荐关注用户数量排行榜
	 * </pre>
	 * 
	 * @author lixiaodong
	 * @param offset
	 * @param limit
	 * @param beginDate
	 * @param endDate
	 * @return
	 */
	public Map<String, Object> getScoreRefereeUsersRank(int offset, int limit, String beginDate, String endDate) {
		String sql0 = " select ui.id, ui.nickname nickname, "
				+ " (select count(0) from USER_INFO ui2 where ui2.REFEREE = ui.id) quantity "
				+ " from user_info ui "
				+ " where 1 = 1 ";
				
		Map<String, Object> map = new HashMap<>();
		if (beginDate != null && !"".equals(beginDate)) {
			sql0 += " and TO_CHAR(ui.subscribe_time, 'yyyy-MM-dd HH:mm:ss') > :beginDate";
			map.put("beginDate", beginDate);
		}
		if (endDate != null && !"".equals(endDate)) {
			sql0 += " and TO_CHAR(ui.subscribe_time, 'yyyy-MM-dd HH:mm:ss') < :endDate";
			map.put("endDate", endDate);
		}
		sql0 += " order by quantity desc ";
		String sql = " select rownum position, a.id id, a.NICKNAME, a.quantity quantity from (" + sql0 + ") a ";
		String countSql = "select count(1) from (" + sql0 + ") temp1 ";
		
		return memberRepository.sqlQuery(sql, countSql, map, offset, limit, "total", "rows");
	}
	
	/**
	 * 
	 * 获取推荐下单用户数量排行榜
	 * <pre>
	 * 获取推荐下单用户数量排行榜
	 * </pre>
	 * 
	 * @author lixiaodong
	 * @param offset
	 * @param limit
	 * @param beginDate
	 * @param endDate
	 * @return
	 */
	public Map<String, Object> getScoreRefereeOrdersRank(int offset, int limit, String beginDate, String endDate) {
		String sql0 = " select u.id, u.nickname nickname, "
				+ " (select count(0) from user_info ui where ui.ID in ("
				+ " select oi.user_id from order_info oi where ui.id = oi.USER_ID ";
				
		Map<String, Object> map = new HashMap<>();
		if (beginDate != null && !"".equals(beginDate)) {
			sql0 += " and TO_CHAR(oi.create_time, 'yyyy-MM-dd HH:mm:ss') > :beginDate";
			map.put("beginDate", beginDate);
		}
		if (endDate != null && !"".equals(endDate)) {
			sql0 += " and TO_CHAR(oi.create_time, 'yyyy-MM-dd HH:mm:ss') < :endDate";
			map.put("endDate", endDate);
		}
		sql0 = sql0 + " ) "
			+ " and ui.REFEREE = u.ID) quantity "
			+ " from user_info u "
			+ " where 1 = 1 "
			+ " order by quantity desc ";
		
		String sql = " select rownum position, a.id id, a.NICKNAME, a.quantity quantity from (" + sql0 + ") a ";
		String countSql = "select count(1) from (" + sql0 + ") temp1 ";
		
		return memberRepository.sqlQuery(sql, countSql, map, offset, limit, "total", "rows");
	}
	
	/**
	 * 
	 * 获取用户推荐关注奖励的积分
	 * <pre>
	 * 获取用户推荐关注奖励的积分
	 * </pre>
	 * 
	 * @author lixiaodong
	 * @param offset
	 * @param limit
	 * @param beginDate
	 * @param endDate
	 * @return
	 */
	public Map<String, Object> getScoreRefereeScoresRank(int offset, int limit, String beginDate, String endDate) {
		String sql0 = " select u.id, u.nickname nickname, "
				+ " (select nvl(sum(score),0) from score_record sr "
				+ " where sr.TYPE = 1 and sr.IS_DELETED = 0 and sr.USER_ID = u.ID ";
				
		Map<String, Object> map = new HashMap<>();
		if (beginDate != null && !"".equals(beginDate)) {
			sql0 += " and TO_CHAR(sr.create_time, 'yyyy-MM-dd HH:mm:ss') > :beginDate";
			map.put("beginDate", beginDate);
		}
		if (endDate != null && !"".equals(endDate)) {
			sql0 += " and TO_CHAR(sr.create_time, 'yyyy-MM-dd HH:mm:ss') < :endDate";
			map.put("endDate", endDate);
		}
		sql0 = sql0 + " ) quantity "
			+ " from user_info u "
			+ " where 1 = 1 "
			+ " order by quantity desc ";
		
		String sql = " select rownum position, a.id id, a.NICKNAME, a.quantity quantity from (" + sql0 + ") a ";
		String countSql = "select count(1) from (" + sql0 + ") temp1 ";
		
		return memberRepository.sqlQuery(sql, countSql, map, offset, limit, "total", "rows");
	}

	
}
